import { HashService } from '@app/hash';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import prisma from '@repo/database';

export interface JwtPayload {
  sub: string;
  crypto: string
}

@Injectable()
export class AuthPowerService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly hashService: HashService,
  ) { }


  async validate({ sub, crypto }: JwtPayload) {
    // 暂时返回null，因为sys_user模型不存在
    return null;
    // const user = await prisma.sys_user.findUnique({
    //   where: {
    //     id: sub
    //   },
    //   include: {
    //     // roles: {
    //     //   include: {
    //     //     role: {
    //     //       include: {
    //     //         menus: {
    //     //           include: {
    //     //             menu: true
    //     //           }
    //     //         }
    //     //       }
    //     //     }
    //     //   }
    //     // },
    //     department: true
    //   }
    // })
    // if (!user) return null;
    // if (!this.comparePassword(user.password!, crypto)) return null;
    // return user;
  }
  /**
   * 生成JWT Token
   */
  generateToken(user: any) {
    const payload: JwtPayload = {
      sub: user.uid,
      crypto: this.hashPassword(user.passport)
    };
    return this.jwtService.sign(payload);
  }

  /**
   * 密码加密
   */
  hashPassword(password: string) {
    const { salt, hash } = this.hashService.cryptoPassword(password);
    return `${salt}:${hash}`
  }

  /**
   * 密码验证
   */
  comparePassword(password: string, hashedPassword: string) {
    const [salt, hash] = hashedPassword.split(':');
    return this.hashService.verifyPassword(password, salt, hash);
  }
}
